package it.softphone.commons.spring.config.plugin;

import it.softphone.commons.service.LogAware;

import java.util.Collections;


import org.apache.commons.configuration.Configuration;
import org.apache.commons.lang.NullArgumentException;
import org.springframework.config.java.valuesource.ValueResolutionException;
import org.springframework.config.java.valuesource.ValueResolver;

public class ConfigurationValueResolver implements ValueResolver, LogAware{
	
	final Configuration conf;
	
	protected ConfigurationValueResolver(Configuration conf) {
		super();
		if( conf == null ) throw new NullArgumentException("conf");
		this.conf = conf;
	}

	@SuppressWarnings("unchecked")
	public <T> T resolve(String name, Class<?> requiredType) throws ValueResolutionException {
		
		T result = null;
		
		if( String.class.equals(requiredType)) {
			result =  (T)conf.getString(name);
		}
		else if( Configuration.class.isAssignableFrom(requiredType) ) {
			result = (T)conf.subset(name);
		}
		else if( Boolean.class.isAssignableFrom(requiredType) && Boolean.TYPE.isAssignableFrom(requiredType)) {
			result = (T)conf.getBoolean(name, Boolean.FALSE);
		}
		else if( Integer.class.isAssignableFrom(requiredType) && Integer.TYPE.isAssignableFrom(requiredType)) {
			result = (T)conf.getInteger(name, new Integer(0));
		}
		else if( java.util.List.class.isAssignableFrom(requiredType) ) {
			result = (T)conf.getList(name, Collections.emptyList());
		}

		if( logger.isTraceEnabled() ) {
			logger.trace( String.format( "ConfigurationValueResolver( [%s], [%s] )=" + result, name, requiredType));
		}
		return result;
	}

}
